<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <avue-crud 
        ref="crud" 
        v-model="form" 
        :page="page" 
        :data="tableData" 
        :table-loading="tableLoading"
        :option="tableOption" 
        :before-open="handleOpenBefore" 
        @on-load="getList" 
        @search-change="searchChange"
        @search-reset="resetsearch" 
        @refresh-change="refreshChange" 
        @size-change="sizeChange"
        @current-change="currentChange" 
        @row-update="handleUpdate" 
        @row-save="handleSave" 
        @row-del="rowDel">
        <template #relList-form = {row}>
          <el-button type="primary" icon="el-icon-setting" @click="pageOpen(row)">配置</el-button>
        </template>
      </avue-crud>
      <el-row :gutter="10">
        <el-col  v-for="(item, index) in myCompsList" :key="index" :span="item.width" :style="{height: item.height + 'px'}">
          <component :is="allComps[item.key]" :style="{height: item.height + 'px'}" />
        </el-col>
      </el-row>
    </div>
    <el-drawer
      v-model="dialogVisible"
      title="页面设计"
      direction="rtl"
      size="80%"
      @close="drawerClose"
    >
    <div class="page-drawer">
      <el-row :gutter="10" class="row-height">
        
        <el-col :span="5" class="row-height">
          <div class="col-item">
            <div class="set-title"><span></span><span>组件集合</span></div>
            <div class="set-content">
              <el-scrollbar>
                <draggable
                  :list="list1" 
                  animation="300"
                  item-key="id"
                  class="list-group"
                  :group="{name: 'item', pull: true, put: false}"
                  filter=".undraggable"
                >
                  <template #item="{ element }">
                    <div class="list-group-item" :class="[element.undraggable ? 'undraggable':'']">
                      {{ element.compZh }}
                    </div>
                  </template>
                </draggable>
              </el-scrollbar>
            </div>
          </div>
        </el-col>
        <el-col :span="11" class="row-height">
          <div class="col-item">
            <div class="set-title"><span></span><span>面板设计</span></div>
            <div class="set-content">
              <el-scrollbar>
                <draggable 
                  :list="list2" 
                  :sort="true"
                  animation="300"
                  class="list-group el-row" 
                  group="item"
                  item-key="id"
                  >
                    <template #item="{ element, index }" >
                      <el-col :span="element.basic.width" class="row-height">
                        <div class="list-group-width item" :class="[activeIndex == index ? 'item-active': '']" @click="getInfo(element, index)">
                          <span>{{ element.basic.compZh }}</span>
                          <el-icon @click.stop="deleteList(index, element)"><DeleteFilled /></el-icon>
                        </div>
                      </el-col>
                    </template>
                </draggable>
              </el-scrollbar>
            </div>
          </div>
        </el-col>
        <el-col :span="8" class="row-height">
          <div class="col-item">
            <div class="set-title"><span><span></span>属性配置</span><el-button class="save-btn"  type="primary" icon="el-icon-setting" @click="savePageSetting">保存</el-button></div>
            <div class="set-content">
              <el-scrollbar>
                <avue-form v-model="dialogForm" :option="dialogOption">
                  <template #name>
                    <el-input v-model="dialogForm.name" placeholder="请输入标题" disabled  @input="nameChange" />
                  </template>
                  <template #display>
                    <el-checkbox v-model="dialogForm.display" label="是否显示标题" @change="displayChange" />
                  </template>
                  <template #width>
                    <el-slider v-model="dialogForm.width"  size="small" @change="widthChange" show-stops :max="24" :min="1" />
                  </template>
                  <template #height>
                    <el-input v-model="dialogForm.height"   @change="heightChange" type="number" />
                  </template>
                </avue-form>
                <form-label ref="pageForm" v-if="compName" :dataJson="allJson[compName]"/>
              </el-scrollbar>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" name="systemSetting" setup>
import {
  fetchList, putObj, addObj, delObj
} from '/@/api/basiciot/yunwei/pagesettings';
import { fetchList as componentList } from '/@/api/basiciot/yunwei/componentsettings';
import { tableOption } from '/@/crud/yunwei/pageSetting';

import { validateNull } from '/@/utils/validate';
import { useMessage, useMessageBox } from '/@/hooks/message';
import allComps from '/@/views/admin/yunwei/pagesetting/utils/getComponentWidget';


import allJson from '/@/views/admin/yunwei/pagesetting/params/js/getJson';

const FormLabel = defineAsyncComponent(() => import('./params/label.vue'));


const form:any = ref({})
const tableLoading = ref(false)
const dialogVisible = ref(false)
const page:any = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10, // 每页显示多少条
})


let list1:any = ref([])
let list2:any = ref([])
let tableData = ref([])
let openType = ref('')
let pageForm = ref()
const activeIndex:any = ref(-1)
const compId = ref()
const compName = ref()



const dialogForm:any = ref({})
const dialogOption = ref({
  span: 24,
  emptyBtn: false,
  submitBtn: false,
  submitText: '保存',
  column: [
    {
      label: '标题',
      prop: 'name'
    },
    {
      label: '显隐',
      prop: 'display',
    },
    {
      label: '宽度',
      prop: 'width'
    },
    {
      label: '高度',
      type: 'number',
      prop: 'height'
    }
  ]
})


onMounted(() => {
})


const allCompsList = computed(() => {
	const list = []
	for (const [key, { title, description }] of Object.entries(allComps)) {
		list.push({ key, title, description });
	}
	return list;
});

// const myCompsList = computed(() => {
// 	// 支持列表
// 	const myGrid = [
// 		'building-img', 'project-view'
// 	];
//   console.log(allComps)
//   console.log(allCompsList.value)
//   console.log(allCompsList.value.filter((item) =>  myGrid.includes(item.key)))
// 	return allCompsList.value.filter((item) =>  myGrid.includes(item.key));
// });
const myCompsList:any = ref([])
console.log(allJson)
const pageOpen = (obj:any) => {
  getCompoenetList()
  dialogVisible.value = true

 
  
  if(openType.value == 'add') {
    list2.value = []
    dialogForm.value.name = ''
    dialogForm.value.width = 12 
    dialogForm.value.height = null
    dialogForm.value.display = true
  } 
}
const drawerClose = () => {
}
const resetList1 = () => {
  list1.value.forEach((obj:any) => {
    obj.undraggable = false
    list2.value.forEach((item:any) => {
      if(obj.id == item.compId) {
        obj.undraggable = true
      }
    })
  })
}
const savePageSetting = () => {
  if(!validateNull(compId.value)){
    list2.value.filter((item:any) => { return item.compId == compId.value})[0]['extra'] = JSON.stringify(pageForm.value.form)
    console.log(list2)
    form.value.relList = list2.value
  } else {
    useMessage().error('请选择组件');
    return
  }
  
}
const getInfo = (obj:any,i:number) => {debugger
  activeIndex.value = i
  compId.value = obj.basic.compId
  compName.value = obj.compEn
  dialogForm.value.name = obj.basic.compZh
  dialogForm.value.width = obj.basic.width 
  dialogForm.value.height = obj.basic.height
  dialogForm.value.display = obj.basic.display
}

const nameChange = (val:any) => {
  if(!validateNull(compId.value)){
    list2.value.filter((item:any) => { return item.compId == compId.value})[0].name = val
  }
  
}
const widthChange = (val:number) => {
  if(!validateNull(compId.value)){
    list2.value.filter((item:any) => { return item.compId == compId.value})[0]['basic']['width'] = val
  }
}
const displayChange = (val:boolean) => {
  if(!validateNull(compId.value)){
    list2.value.filter((item:any) => { return item.compId == compId.value})[0]['basic']['display'] = val
  }
}
const heightChange = (val:number) => {
  if(!validateNull(compId.value)){
    list2.value.filter((item:any) => { return item.compId == compId.value})[0]['basic']['height'] = val
  }
}
const deleteList = (index:number, {compId}) => {
  let obj = list2.value.splice(index,1)
  let flag = list1.value.some((obj:any) => {return obj.id == compId})
  if(!flag) {
    list1.value = [...list1.value, ...obj]
  }
  dialogForm.value.name = ''
  resetList1()
}
const getCompoenetList = () => {
  componentList({current: 1, size: 9999}).then(res => {
    list1.value = res.data.records || []
    list1.value.forEach((obj:any) => {
      obj.basic = {
        compZh: obj.compZh,
        compId: obj.id,
        width:  12,
        height:  '',
        display:  true
      }
      obj.compId = obj.id
      obj.undraggable = false
      list2.value.forEach((item:any) => {
        if(obj.id == item.compId) {
          obj.undraggable = true
        }
      })
    })
    console.log(list1.value)
  })
}
//初始化获取数据
const getList = (page: any, params?: object) => {
  tableLoading.value = true;
  fetchList(
    Object.assign(
      {
        current: page.currentPage,
        size: page.pageSize,
      },
      params
    )
  )
    .then((res) => {
      tableLoading.value = false;
      tableData.value = res.data.records || []
      page.total = res.data.total
      myCompsList.value = getPageComponents(res.data.records[2].relList)
    })
    .catch(() => {
      tableLoading.value = false;
    });
}


// 组装页面配置好组件，格式化数据
const getPageComponents = (pageList:any) => {
  let list:any = []
  pageList.forEach((obj:any) => {
    allCompsList.value.forEach((item:any) => {
      if(obj.basic.compEn == item.key) {
        list.push({
          width: obj.basic.width,
          height: obj.basic.height,
          key: item.key,
          display: obj.basic.display,
          title: item.title,
          description: item.description,
          compEn: obj.basic.compEn
        })
      }
    });
  })
  return list
}
//打开弹框
const handleOpenBefore = (show: Function, type: string) => {
  openType.value = type
  if(type == 'edit') {
    list2.value = form.value.relList
  }
  show();
}

const rowDel = (row:any, index:number) => {


  useMessageBox().confirm('是否确认删除' + row.id).then((res) => {


    delObj([row.id]).then(() => {
      useMessage().success('删除成功');
      getList(page);
    })
    .catch((err: any) => {
      useMessage().error(err.msg);
    });

  })
}
//更新操作
const handleUpdate = (row:any, index:number, done:Function, loading:Function) => {
  putObj(row).then((data) => {
  if (data.data) {
      useMessage().success('修改成功');
    } else {
      useMessage().error('修改失败');
    }
    done();
    getList(page);
  })
  .catch(() => {
    loading();
  });
}
//新增操作
const handleSave = (row:any, done:Function, loading:Function) => {
  
  addObj(row)
    .then((res) => {
      if (res.data) {
        useMessage().success('添加成功');
      } else {
        useMessage().success('添加失败');
      }

      done();
      getList(page);
    })
    .catch(() => {
      loading();
    });
}
const sizeChange = (pageSize:number) => {
  page.pageSize = pageSize;
}
const currentChange = (current:number) => {
  page.currentPage = current;
}
const searchChange = (form:object, done:Function) => {
  page.currentPage = 1;
  getList(page, form);
  done();
}
const refreshChange = () => {
  getList(page);
}
const resetsearch = () =>{
}

</script>
<style lang="scss" scoped>
:deep(.el-drawer) {
  // background: #efefef;
  .el-drawer__header {
    // background: #fff;
  }
  .el-drawer__body {
    // background: #fff;
    // background: #efefef;
    padding-top: 0;
  }
}

.page-drawer {
  height: 100%;
  .col-item {
    height: 100%;
    border: 1px solid #eaeaea;
    
    border-radius: 5px;
    box-shadow: inset 0 0 5px #ddd;
  }
  .set-title {
    font-size: 18px;
    padding: 10px;
    border-bottom: 1px solid #eaeaea;
    clear: both;
    .save-btn {
      float: right;
    }
  }
  .set-content {
    padding: 10px;
    height: calc(100% - 48px);
  }
}
.list-group {
  min-height: 100px;
  &-item {
    height: 60px;
    width: 150px;
    // color: red;
    text-align: center;
    line-height: 60px;
    border: 1px solid #ccc;
    border-radius: 5px;
    cursor: pointer;
    margin-bottom: 10px;
    &:hover {
      transition: all .3s;
      border: 1px solid var(--el-color-primary-light-3);
    }
  }
  &-width {
    height: 60px;
    // width: 150px;
    // color: red;
    text-align: center;
    line-height: 60px;
    border: 1px solid #ccc;
    border-radius: 5px;
    cursor: pointer;
    margin-bottom: 10px;
    &:hover {
      transition: all .3s;
      border: 1px solid var(--el-color-primary-light-3);
    }
    .el-icon {
      float: right;
      margin-top: 20px;
      margin-right: 10px;
      font-size: 18px;
    }
  }
  .item-active {
    border: 1px solid var(--el-color-primary-light-3);
  }
  .undraggable {
    color: #999;
    background: #eaeaea;
    cursor: not-allowed;
  }
}
.row-height {
  height: 100%;
}
</style>
